﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace Ession
{
    public class MultiFileReceiver
    {
        public MultiFileReceiver(string fileFullName, int port)
        {
            writeFile = new FileInfo(fileFullName);
            this.port = port;
            //TODO:* alter here

           // var ip = Dns.GetHostAddresses(Dns.GetHostName())[0];
           // lis = new TcpListener(ip, port);
            lis = new TcpListener(IPAddress.Loopback, port);

            
            lis.Start();
            new Thread(() =>
                           {
                               while (true)
                               {
                                   if (lis.Pending())
                                   {
                                       var client = lis.AcceptTcpClient();
                                       using (BinaryReader br = new BinaryReader(client.GetStream()))
                                       {
                                           using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(writeFile.FullName)))
                                           {
                                               var data = new byte[1024];
                                               int readCount = 0;
                                               do
                                               {
                                                   readCount = br.Read(data, 0, data.Length);
                                                   bw.Write(data, 0, readCount);
                                               } while (readCount > 0);
                                               return;
                                           }
                                       }

                                   }
                                   Thread.Sleep(500);
                               }
                           }).Start();
        }
        private TcpListener lis;
        private int port;

        private FileInfo writeFile;
    }
}
